package com.leaves.common.util.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ZipUtil;
import com.leaves.exception.MessageCenterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2021年03月09日  17时06分06秒
 * @Description: 文件工具类
 */
public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 创建多级文件目录
     *
     * @param path 目标路径
     */
    public void createFolder(String path) {
        LOGGER.info("创建多级文件目录 ---->参数：{}", path);
        File dir = new File(path);
        // 判断目录是否存在
        if (!dir.exists()) {
            //创建单级目录
//            dir.mkdir();
            //创建多级目录
            dir.mkdirs();
            LOGGER.info("目录创建成功：" + path);
        }
    }

    /**
     * 压缩目录
     * <p>
     * 将源目标目录（包括其内文件或文件夹）打成压缩包
     *
     * @param zipName      压缩包名称
     * @param resourceName 源文件名称
     * @param PATH
     * @param timestamp    压缩包存放目录
     * @return
     */
    public String toZip(String zipName, String resourceName, String PATH, String timestamp) {
        LOGGER.info("创建多级文件目录 ---->参数1：{}  ||  参数2：{}  || 参数3：{}  ||  参数4：{}", zipName,resourceName,PATH, timestamp);
        //压缩包名称
        String ZIP_NAME = zipName + ".zip";
        LOGGER.info("压缩包名称：" + ZIP_NAME);
        //压缩包所在目录
        String FILE_PATH = PATH + timestamp + "/";
        LOGGER.info("压缩包所在目录：" + FILE_PATH);
        //源目录路径
        String SOURCE_FILE_PATH = PATH + resourceName;
        LOGGER.info("源目录路径：" + SOURCE_FILE_PATH);
        //目标文件路径
        String TARGET_PATH = FILE_PATH + ZIP_NAME;
        LOGGER.info("目标路径：" + TARGET_PATH);
        //创建压缩包所在目录
        createFolder(FILE_PATH);
        LOGGER.info("创建压缩包所在目录：" + FILE_PATH);
        //压缩
        ZipUtil.zip(SOURCE_FILE_PATH, TARGET_PATH);
        LOGGER.info("压缩成功：" + TARGET_PATH);
        return TARGET_PATH;
    }

    /***
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public void delFolder(String folderPath) {
        LOGGER.info("删除文件夹 ---->参数：{}", folderPath);
        try {
            System.out.println("删除完里面所有内容 = folderPath --->" + folderPath);
            // 删除完里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            // 删除空文件夹
            myFilePath.delete();
            System.out.println("删除空文件夹");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public boolean delAllFile(String path) {
        LOGGER.info("删除指定文件夹下所有文件 ---->参数：{}", path);
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                // 先删除文件夹里面的文件
                delAllFile(path + "/" + tempList[i]);
                // 再删除空文件夹
                delFolder(path + "/" + tempList[i]);
                flag = true;
            }
        }
        return flag;
    }


    /**
     * 将URL地址转成File对象
     *
     * @param url URL地址（支持在线文件地址）
     * @return
     * @throws Exception
     */
    public static File urlToFile(String url) throws Exception {
        LOGGER.info("将URL地址转成File对象 --->", url);
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
        httpUrl.connect();
        InputStream ins = httpUrl.getInputStream();
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "xie");//System.getProperty("java.io.tmpdir")缓存
        if (file.exists()) {
            //如果缓存中存在该文件就删除
            file.delete();
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * 将File对象转换为byte[]的
     *
     * @param file File对象
     * @return
     */
    public static byte[] fileToByte(File file) {
        LOGGER.info("将File对象转换为byte[] --->", file);
        FileInputStream fileInputStream = null;
        byte[] byteData = null;
        try {
            byteData = new byte[(int) file.length()];
            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(byteData);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return byteData;
    }

    /**
     * 写入文件到请求的返回体中
     *
     * @param file
     * @param response
     * @param request
     * @throws Exception
     */
    public static void writeFile(File file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        LOGGER.info("根据文件对象写入文件到请求的返回体中 --->", file);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        fis = new FileInputStream(file);
        request.setCharacterEncoding("UTF-8");
        String agent = request.getHeader("User-Agent").toUpperCase();
        if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
            fileName = URLEncoder.encode(fileName, "UTF-8");
        else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public");
        ServletOutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = fis.read(b)) != -1) {
            out.write(b, 0, len);
        }
        response.flushBuffer();
        fis.close();
    }

    /**
     * 写入文件到请求的返回体中
     *
     * @param url      （支持在线文件地址）
     * @param response
     * @param request
     * @throws Exception
     */
    public static void writeFile(String url, HttpServletResponse response, HttpServletRequest request) throws Exception {
        LOGGER.info("根据文件地址写入文件到请求的返回体中 --->", url);
        File file = urlToFile(url);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        fis = new FileInputStream(file);
        request.setCharacterEncoding("UTF-8");
        String agent = request.getHeader("User-Agent").toUpperCase();
        if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
            fileName = URLEncoder.encode(fileName, "UTF-8");
        else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public");
        ServletOutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = fis.read(b)) != -1) {
            out.write(b, 0, len);
        }
        response.flushBuffer();
        fis.close();
    }

    /**
     * 文件下载
     *
     * @param path     文件路径
     * @param response 返回消息
     * @return
     */
    public void downFile(String path, HttpServletResponse response) {
        LOGGER.info("文件下载：" + path);
        //获取文件名    引用hutool工具类库
        String filename = FileNameUtil.getName(FileUtil.file(path));
        LOGGER.info("文件名称：" + filename);
        File file = new File(path);
        if (file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                // 设置强制下载不打开
                response.setContentType("application/force-download;charset=UTF-8");
                // 设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + filename);
                // 设置信息给客户端不解析
                String type = new MimetypesFileTypeMap().getContentType(filename);
//              设置contenttype，即告诉客户端所发送的数据属于什么类型
                response.setHeader("Content-type", type);
//              设置编码
                String hehe = new String(filename.getBytes("utf-8"), "iso-8859-1");
//              设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
                response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (FileNotFoundException fe) {
                fe.printStackTrace();
                LOGGER.error("### 下载的文件不存在 ###");
                throw new MessageCenterException("下载的文件不存在", fe);
            } catch (IOException ie) {
                ie.printStackTrace();
                LOGGER.error("### 文件下载出错啦 ###");
                throw new MessageCenterException("下载的文件不存在", ie);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            LOGGER.error("### 文件下载出错啦 ###");
            throw new MessageCenterException("文件下载出错啦");
        }
    }
}
